var ajax = require('../../utils/ajax.js');
var util = require('../../utils/util.js');
var Base = require('../base.js');
var app = getApp();
var curPage;
var curScope;
var _timerId;
var _timerList = {};

function init({
  page,
  scope,
}) {
  curPage = page;
  curScope = scope || 'seckillList';

  _initData();
}

function _initData() {
  ajax.G('/openapi/CActivity/flashActList', {}, function(data) {
    var actModList = data.result.actList;

    actModList.forEach(function(actMod, modIndex) {
      actMod.list.forEach(function(actItem, index) {
        var leftTime = actItem.state == 0 ? actItem.begin_left_time : actItem.left_time;

        if (leftTime > 0) {
          _timerList[modIndex + '|' + index] = leftTime;
        }

        actItem.percent = Math.round(actItem.sale_amount / actItem.goods_amount * 100);
      });
    });

    _setData({
      actModList,
      timerStrs: {}
    });

    if (_timerId) {
      clearTimeout(_timerId);
    }
    _timerDown();
  });
}

function _timerDown() {
  var timerStrs = _getData('timerStrs');
  var isOver = false;
  var _timerListKeys = Object.keys(_timerList);

  if (_timerListKeys.length == 0) {
    return;
  }
  _timerListKeys.some(function(key) {
    var sec = _timerList[key];

    timerStrs[key] = util.getTimeBySec(sec);

    if (sec == 0) {
      isOver = true;
      return true;
    }
    _timerList[key] = --sec;
  });

  if (isOver) {
    _flushAct();
    clearTimeout(_timerId);
    return;
  }
  _setData({
    timerStrs,
  });
  _timerId = setTimeout(() => {
    _timerDown();
  }, 1000);
}

//刷新活动
function _flushAct() {
  _initData();
}

function _setData(data) {
  var obj = _getData();

  Object.assign(obj, data);

  curPage.setData({
    [`${curScope}`]: obj
  });
}

function _getData(key) {
  var data = curPage.data[`${curScope}`] || {};

  if (!key) {
    return data;
  } else {
    return data[key];
  }
}


module.exports = {
  init
};